// pages/goodsdetails/goodsdetails.js
var WxParse = require('../../wxParse/wxParse.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {

    //轮播属性
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 1000,

   //商品详情
    goodsDetail: {}, 
    buyNumMax:0,
    buyNumMin:0,
    buyNumber:0,

   //规格按钮相关属性
    hasMoreSelect: true,
    hideShopPopup: true,

    //评论
    reputation: {},

   //选择商品规格
    selectSizePrice: 0,//选中属性后的价格
    propertyChildIds: {},//选中属性后的属性id
    propertyChildNames: {},//选中属性后的属性名称
  
   //是否可提交
    canSubmit: false,

    shopNum: 0,//购买数量
    shopCarInfo:{}//购物车信息
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    var that = this;

    // 获取购物车数据
    wx.getStorage({
      key: 'shopCarInfo',
      success: function (res) {
        that.setData({
          shopCarInfo: res.data,
          shopNum: res.data.shopNum
        });
      }
    })
    
    //请求商品详情信息
    wx.request({
      url: 'https://api.it120.cc/tz/shop/goods/detail',
      data: {
        id: e.id
      },
      success: function (res) {

        //商品详情
        var goodsDetail = res.data.data;

        //商品规格
        var properties = goodsDetail.properties;

        //拼接可选择的规格
        if (properties) {
          var selectPropertieName = "";
          for (var i = 0; i < properties.length; i++) {
            selectPropertieName = selectPropertieName + " " + properties[i].name;
          }

          that.setData({
            hasMoreSelect: true,
            selectSize:"选择:" + selectPropertieName,//在“选择”后加规格名称（如尺码颜色）
          });
        }
       
        //商品基础信息
        var basicInfo = goodsDetail.basicInfo;

        that.setData({
          goodsDetail: goodsDetail,   //商品详情
          basicInfo: basicInfo,//商品基础信息
          selectSizePrice: basicInfo.minPrice, //价格
          buyNumMax: basicInfo.stores, //最多可购买数
          buyNumber: (basicInfo.stores > 0) ? 1 : 0  //最少购买数
        });

        //展示商品详情图片
        WxParse.wxParse('article', 'html', goodsDetail.content, that, 5);

         //显示评论
         that.reputation(e.id);
      }
    })
  },

  //商品评论
  reputation: function (goodsId) {
    var that = this;
    wx.request({
      url: 'https://api.it120.cc/tz/shop/goods/reputation',
      data: {
        goodsId: goodsId
      },
      success: function (res) {
        if (res.data.code == 0) {
          that.setData({
            reputation: res.data.data
          });
        }
      }
    })
  },

  /**
   * 规格选择弹出框
   */
  bindGuiGeTap: function () {
    this.setData({
      hideShopPopup: false
    })
  },

  /**
 * 规格选择弹出框隐藏
 */
  closePopupTap: function () {
    this.setData({
      hideShopPopup: true
    })
  },

   /**
   * 选择商品规格
   */
  labelItemTap: function(e) {
    var that = this;
   
    //获取选中规格父类index
    var propertyindex = e.currentTarget.dataset.propertyindex;

    //获取选中规格父类
    var properties = that.data.goodsDetail.properties[propertyindex];

    //所有的规格
    var detaiProperties = that.data.goodsDetail.properties;

    // 取消该分类下的子栏目所有的选中状态
    var childs = properties.childsCurGoods;
    for(var i = 0;i < childs.length;i++){
       properties.childsCurGoods[i].active = false;
    }

    // 设置当前选中状态
    var propertychildindex = e.currentTarget.dataset.propertychildindex;
    properties.childsCurGoods[propertychildindex].active = true;

    // 获取所有规格种类总数
    var needSelectNum = detaiProperties.length;

   //选中的规格种类数
    var curSelectNum = 0;

   //规格属性id
    var propertyChildIds= "";

    //规格属性名称（如粉色）
    var propertyChildNames = "";

    //循环所有规格种类，查看如果其子类有选中，则当前选中的规格数curSelectNum加1，并且保存选中的子属性id和名称
    for (var i = 0; i < needSelectNum;i++) {

      childs = detaiProperties[i].childsCurGoods;

    //循环规格父类下所有属性
      for (var j = 0;j < childs.length;j++) {detaiProperties
        if(childs[j].active){
          curSelectNum++;
          propertyChildIds = propertyChildIds + detaiProperties[i].id + ":"+ childs[j].id +",";
          propertyChildNames = propertyChildNames + detaiProperties[i].name + ":"+ childs[j].name +"  ";
        }
      }
    }

   //每一种种类的规格都选了后才能加入购物车或立即购买
    var canSubmit = false;
    if (needSelectNum == curSelectNum) {
      canSubmit = true;
    }

    // 根据规格子属性id和货品id，获取货品价格
    if (canSubmit) {
      wx.request({
        url: 'https://api.it120.cc/tz/shop/goods/price',
        data: {
          goodsId: that.data.goodsDetail.basicInfo.id,
          propertyChildIds:propertyChildIds
        },
        success: function(res) {
          that.setData({
            selectSizePrice:res.data.data.price,//选中属性后的价格
            propertyChildIds:propertyChildIds,//选中属性后的属性id
            propertyChildNames:propertyChildNames,//选中属性后的属性名称
            buyNumMax:res.data.data.stores,//最多可以买
            buyNumber:(res.data.data.stores>0) ? 1: 0//购买数量
          });
        }
      })
    }

    //设置商品详情和是否可提交购买
    this.setData({
      goodsDetail: that.data.goodsDetail,
      canSubmit:canSubmit
    })  
  },


  /**
* 加入购物车
*/
  addShopCar: function () {
    if (this.data.goodsDetail.properties) {
      if (!this.data.canSubmit) {
        wx.showModal({
          title: '提示',
          content: '请选择商品规格！',
          showCancel: false
        })
        this.bindGuiGeTap();
        return;
      }
    }
    if (this.data.buyNumber < 1) {
      wx.showModal({
        title: '提示',
        content: '购买数量不能为0！',
        showCancel: false
      })
      return;
    }

    //组建购物车
    var shopCarInfo = this.bulidShopCarInfo();

    this.setData({
      shopCarInfo: shopCarInfo,
      shopNum: shopCarInfo.shopNum
    });

    // 写入本地存储
    wx.setStorage({
      key: "shopCarInfo",
      data: shopCarInfo
    })

    this.closePopupTap();
    wx.showToast({
      title: '加入购物车成功',
      icon: 'success',
      duration: 2000
    })
  },
  
  /**
 * 规格选择弹出框
 */
  bindGuiGeTap: function () {
    this.setData({
      hideShopPopup: false
    })
  },

  /**
 * 组建购物车信息
 */
  bulidShopCarInfo: function () {

    var basicInfo = this.data.goodsDetail.basicInfo;

    // 加入购物车
    var shopCarMap = {};
    shopCarMap.goodsId = basicInfo.id;
    shopCarMap.pic = basicInfo.pic;
    shopCarMap.name = basicInfo.name;
    shopCarMap.weight = basicInfo.weight;
    shopCarMap.propertyChildIds = this.data.propertyChildIds;
    shopCarMap.label = this.data.propertyChildNames;
    shopCarMap.price = this.data.selectSizePrice;
    shopCarMap.left = "";
    shopCarMap.active = true;
    shopCarMap.number = this.data.buyNumber;
    shopCarMap.logisticsType = basicInfo.logisticsId;
    shopCarMap.logistics = this.data.goodsDetail.logistics;
   

   //原购物车信息
    var shopCarInfo = this.data.shopCarInfo;
  
    if (!shopCarInfo.shopNum) {
        shopCarInfo.shopNum = 0;
    }

    if (!shopCarInfo.shopList) {
      shopCarInfo.shopList = [];
    }

    //依次循环原购物车信息，与当前加入购物车的货品对比，相同则只将购买数量相加，并用hasSameGoodsIndex记录该相同货品在原购物车中的位置（即i）
    var hasSameGoodsIndex = -1;
    for (var i = 0; i < shopCarInfo.shopList.length; i++) {
      var tmpShopCarMap = shopCarInfo.shopList[i];
      var sameGood = tmpShopCarMap.goodsId == shopCarMap.goodsId;//相同货品
      var sameProperties = tmpShopCarMap.propertyChildIds == shopCarMap.propertyChildIds;//相同规格
      if (sameGood && sameProperties) {
        hasSameGoodsIndex = i;
        shopCarMap.number = shopCarMap.number + tmpShopCarMap.number;
        break;
      }
    }

    //修改购物车信息，原来购物车已有相同货品，则替换，如果原来购物车没有相同货品，则直接在原来的基础上加
    shopCarInfo.shopNum = shopCarInfo.shopNum + this.data.buyNumber;

    if (hasSameGoodsIndex > -1) {//原来购物车有货品，用当前要加的货品信息替代原购物车信息
      shopCarInfo.shopList.splice(hasSameGoodsIndex, 1, shopCarMap);
    } else {//原来购物车没有货品，直接加就好啦
      shopCarInfo.shopList.push(shopCarMap);
    }
    return shopCarInfo;
  },

  //减购买数量
  numJianTap: function () {
    if (this.data.buyNumber > this.data.buyNumMin) {
      var currentNum = this.data.buyNumber;
      currentNum--;
      this.setData({
        buyNumber: currentNum
      })
    }
  },

//加购买数量
  numJiaTap: function () {
    if (this.data.buyNumber < this.data.buyNumMax) {
      var currentNum = this.data.buyNumber;
      currentNum++;
      this.setData({
        buyNumber: currentNum
      })
    }
  },

  /**
  * 立即购买
  */
  buyNow: function () {
    if (this.data.goodsDetail.properties) {
      if (!this.data.canSubmit) {
        wx.showModal({
          title: '提示',
          content: '请选择商品规格！',
          showCancel: false
        })
        this.bindGuiGeTap();
        return;
      }
    }
    if (this.data.buyNumber < 1) {
      wx.showModal({
        title: '提示',
        content: '购买数量不能为0！',
        showCancel: false
      })
      return;
    }

    //组建立即购买信息
    var buyNowInfo = this.buliduBuyNowInfo();

    // 写入本地存储
    wx.setStorage({
      key: "buyNowInfo",
      data: buyNowInfo
    })

    this.closePopupTap();

    wx.navigateTo({
      url: "/pages/to-pay-order/to-pay-order?orderType=buyNow"
    })
  },

  /**
 * 组建立即购买信息
 */
  buliduBuyNowInfo: function () {
    var shopCarMap = {};

    var basicInfo = this.data.goodsDetail.basicInfo;

    shopCarMap.goodsId = basicInfo.id;
    shopCarMap.pic = basicInfo.pic;
    shopCarMap.name = basicInfo.name;
    shopCarMap.logisticsType = basicInfo.logisticsId;
    shopCarMap.weight = basicInfo.weight;

    shopCarMap.propertyChildIds = this.data.propertyChildIds;
    shopCarMap.label = this.data.propertyChildNames;
    shopCarMap.logistics = this.data.goodsDetail.logistics;
    shopCarMap.price = this.data.selectSizePrice;
    shopCarMap.number = this.data.buyNumber;
    shopCarMap.left = "";
    shopCarMap.active = true;
    
    var buyNowInfo = {};
    if (!buyNowInfo.shopNum) {
      buyNowInfo.shopNum = 0;
    }
    if (!buyNowInfo.shopList) {
      buyNowInfo.shopList = [];
    }
    buyNowInfo.shopList.push(shopCarMap);
    return buyNowInfo;
  },   

  //没选规格就点加入购物车
  toAddShopCar: function () {
    this.setData({
      shopType: "addShopCar"
    })
    this.bindGuiGeTap();
  },

//没选规格就点立即购买
  tobuy: function () {
    this.setData({
      shopType: "tobuy"
    });
    this.bindGuiGeTap();
  },  
})